package com.polaris.live.dialog

import android.content.Context
import android.view.View
import android.view.ViewGroup
import com.blankj.utilcode.util.ColorUtils
import com.blankj.utilcode.util.StringUtils
import com.bumptech.glide.Glide
import com.bumptech.glide.load.engine.DiskCacheStrategy
import com.bumptech.glide.load.resource.bitmap.RoundedCorners
import com.lxj.xpopup.XPopup
import com.lxj.xpopup.core.BottomPopupView
import com.polaris.live.R
import com.polaris.live.common.constant.AppConst
import com.polaris.live.common.ext.autoDp
import com.polaris.live.common.ext.setOnSingleClickListener
import com.polaris.live.common.mvvm.viewmodel.BaseViewModel
import com.polaris.live.common.network.request
import com.polaris.live.common.network.requestLoading
import com.polaris.live.common.util.LogExt
import com.polaris.live.common.util.NavigationBarUtils
import com.polaris.live.common.util.ToastGravity
import com.polaris.live.common.util.ViewUtils
import com.polaris.live.databinding.DialogRoomBackgroundUpLoadBinding
import com.polaris.live.dialog.common.ConfirmCanalDialog
import com.polaris.live.interface_bag.S3UploadCallback
import com.polaris.live.net.userService
import com.polaris.live.popup.SelectImagePopup
import com.polaris.live.resp.back_resp.UserPartyBackgroundVo
import com.polaris.live.resp.go_resp.UpLoadBackgroundRequest
import com.polaris.live.resp.go_resp.UserPartyBackgroundSaveRequest
import com.polaris.live.translation.R.string
import com.polaris.live.utils.CropUtils
import com.polaris.live.utils.image.ImageUtils
import com.polaris.live.utils.image.loadImage

/**
 * RoomBackgroundUpLoadDialog
 *
 * @author Created by 半仙 on 2024/12/21/021 15:16
 */
class RoomBackgroundUpLoadDialog(
    context: Context,
    private val mViewModel: BaseViewModel,
    private val mMaxUploadTimes: Int,
    private val mCurrentUploadTimes: Int,
    private val mItem: UserPartyBackgroundVo,
    private val mOnUpLoadSuccessCallback: () -> Unit,
) : BottomPopupView(context) {

    override fun getImplLayoutId() = R.layout.dialog_room_background_up_load

    private lateinit var mBinding: DialogRoomBackgroundUpLoadBinding

    private var mState: Int? = null

    //这个token有值就代表上传成功过，但是没有保存
    private var mToken: String? = null

    override fun onCreate() {
        super.onCreate()
        mBinding = DialogRoomBackgroundUpLoadBinding.bind(popupImplView)
        mBinding.tvUpload.alpha = 0.4f
        if (mItem.background?.isNotEmpty() == true) {
            Glide.with(context).loadImage(mItem.background).transform(RoundedCorners(4.autoDp))
                .into(mBinding.ivBackground)
            mBinding.ivAdd.visibility = View.GONE

            //审核中
            if (mItem.auditStatus == AppConst.CoverPhoto.UNDER_REVIEW) {
                mBinding.tvReplace.visibility = View.VISIBLE
                setStateUI(UNDER_REVIEW, StringUtils.getString(string.manual_review))
            }
        }
        mBinding.tvTodayUpTimes.text =
            StringUtils.getString(string.today_up_times, (mMaxUploadTimes - mCurrentUploadTimes).toString())

        val lp = mBinding.bottomLine.layoutParams as ViewGroup.LayoutParams
        lp.height = NavigationBarUtils.getNavigationBarHeight(context)
        mBinding.bottomLine.layoutParams = lp

        initListener()
    }

    private fun initListener() {
        mBinding.btnClose.setOnSingleClickListener {
            onClickBack()
        }
        mBinding.tvUpload.setOnSingleClickListener {
            if (mToken.isNullOrEmpty()) {
                ToastGravity.showGravity(StringUtils.getString(string.please_frist_up_load_photo))
                return@setOnSingleClickListener
            }
            if (mState != UPLOAD_SUCCESS) {
                ToastGravity.showGravity(StringUtils.getString(string.photo_is_uploading_dont_save))
                return@setOnSingleClickListener
            }
            mToken?.let { it1 -> saveBackground(it1) }
        }
        mBinding.ivBackground.setOnSingleClickListener {
            if (mCurrentUploadTimes == mMaxUploadTimes) {
                ToastGravity.showGravity(
                    StringUtils.getString(string.you_one_day_upload_to_upper_limit, mMaxUploadTimes.toString())
                )
                return@setOnSingleClickListener
            }
            showPhotoSelect()
        }
        mBinding.viewPleaseHolder.setOnSingleClickListener {
            onClickBack()
        }
    }

    private fun showPhotoSelect() {
        val activity = ViewUtils.getAliveTopActivity() ?: return
        XPopup.Builder(context)
            .moveUpToKeyboard(false)
            .isDestroyOnDismiss(true)
            .asCustom(SelectImagePopup(context, onSelectIt = { type ->
                when (type) {
                    SelectImagePopup.CAMERA -> {
                        CropUtils.startCameraCrop(activity, 750f, 1624f, 750, 1624, {
                            uploadPhoto(it)
                        }, {})
                    }

                    else -> {
                        CropUtils.startAlbum(activity, {
                            uploadPhoto(it)
                        }, {}, 750f, 1624f, 750, 1624)
                    }
                }
            }))
            .show()
    }

    override fun onBackPressed(): Boolean {
        onClickBack()
        return false
    }

    private fun onClickBack() {
        if (!mToken.isNullOrEmpty()) {
            XPopup.Builder(context)
                .isDestroyOnDismiss(true)
                .asCustom(
                    ConfirmCanalDialog(context,
                        StringUtils.getString(string.you_photo_not_save_sure_leave),
                        StringUtils.getString(string.submit_and_back),
                        onConfirmCallback = {
                            mToken?.let { it1 -> saveBackground(it1) }
                        },
                        onCanalCallback = {
                            dismiss()
                        }
                    )
                ).show()
        } else {
            dismiss()
        }
    }

    //图片上传
    private fun uploadPhoto(photoUrl: String) {
        mToken = null
        mBinding.ivAdd.visibility = View.GONE
        mBinding.tvReplace.visibility = View.GONE
        //图片上传中
        Glide.with(context).load(photoUrl).transform(RoundedCorners(4.autoDp))
            .skipMemoryCache(true)
            .diskCacheStrategy(DiskCacheStrategy.NONE)
            .into(mBinding.ivBackground)

        setStateUI(UPLOADING, StringUtils.getString(string.photo_up_loading))

        ImageUtils.s3Upload(photoUrl, AppConst.UpLoad.ROOM_BANCGROUDN_DIY, 1024, callback =
        object : S3UploadCallback {
            override fun onSuccess(
                url: String,
                size: Pair<Int, Int>?,
            ) {
                //上传成功ai审核中
                setStateUI(UPLOAD_SUCCESS, StringUtils.getString(string.upload_succee))
                upLoadBackground(url, mItem.position)
            }

            override fun onFailure(t: Throwable) {
                LogExt.logE("--net", t)
                //图片上传失败
                setStateUI(UPLOAD_ERROR, StringUtils.getString(string.photo_not_good_please_change))
                ToastGravity.showGravity(t.message)
            }
        })
    }

    private fun setStateUI(state: Int, content: String) {
        mState = state
        mBinding.ivUploadTips.visibility = View.VISIBLE
        mBinding.tvUploadTips.visibility = View.VISIBLE
        mBinding.tvUploadTips.text = content
        mBinding.tvUpload.alpha = 0.4f
        when (state) {
            UPLOADING -> {//上传中
                mBinding.ivUploadTips.visibility = View.GONE
                mBinding.tvUploadTips.setTextColor(ColorUtils.getColor(R.color.color_ff43c158))
            }

            UPLOAD_SUCCESS -> {//上传成功
                mBinding.ivUploadTips.setImageResource(com.polaris.live.common.R.drawable.ic_correct)
                mBinding.tvUploadTips.setTextColor(ColorUtils.getColor(R.color.color_ff43c158))
                mBinding.tvUpload.alpha = 1f
            }

            UPLOAD_ERROR -> {//上传失败
                mBinding.ivUploadTips.setImageResource(R.drawable.ic_delete_account_warn_red)
                mBinding.tvUploadTips.setTextColor(ColorUtils.getColor(R.color.color_fffe4f3c))
            }

            UNDER_REVIEW -> {//审核中
                mBinding.ivUploadTips.setImageResource(R.drawable.ic_under_review_icon)
                mBinding.tvUploadTips.setTextColor(ColorUtils.getColor(R.color.color_ff0095ff))
            }
        }
    }

    //上传派对背景
    private fun upLoadBackground(path: String, position: Int) {
        mViewModel.request({ userService.partyBackgroundUpload(UpLoadBackgroundRequest(path, position)) }, {
            mToken = it.toString()
            mBinding.tvReplace.visibility = View.VISIBLE
            setStateUI(UPLOAD_SUCCESS, StringUtils.getString(string.ai_is_ok))
        }, {
            setStateUI(UPLOAD_ERROR, it.errorMsg)
        })
    }

    //保存派对背景
    private fun saveBackground(token: String) {
        mBinding.tvUpload.isClickable = false
        mViewModel.requestLoading({ userService.partyBackgroundSave(UserPartyBackgroundSaveRequest(token)) }, {
            mBinding.tvUpload.isClickable = true
            ToastGravity.showGravity(StringUtils.getString(string.photo_upload_success_please_wait))
            mOnUpLoadSuccessCallback.invoke()
            dismiss()
        }, {
            mBinding.tvUpload.isClickable = true
            setStateUI(UPLOAD_ERROR, it.errorMsg)
        })
    }

    companion object {

        //仅本dialog给文字用的类型
        const val UPLOADING = 1         //上传中
        const val UNDER_REVIEW = 2      //审核中
        const val UPLOAD_ERROR = 3      //上传失败 or 保存失败
        const val UPLOAD_SUCCESS = 4    //上传成功 or 保存成功

        fun show(
            context: Context,
            viewModel: BaseViewModel,
            maxUploadTimes: Int,
            currentUploadTimes: Int,
            item: UserPartyBackgroundVo,
            onUpLoadSuccessCallback: () -> Unit,
        ) {
            XPopup.Builder(context)
                .isDestroyOnDismiss(true)
                .enableDrag(false)
                .asCustom(
                    RoomBackgroundUpLoadDialog(
                        context,
                        viewModel,
                        maxUploadTimes,
                        currentUploadTimes,
                        item,
                        onUpLoadSuccessCallback
                    )
                )
                .show()
        }
    }
}